// store/index.js - 兼容 Vue2 和 Vue3
let store

// #ifndef VUE3
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

store = new Vuex.Store({
    state: {
        // 用户登录状态
        isLoggedIn: false,
        // 用户信息
        userInfo: {
            token: '',
            member_info: {}
        }
    },

    mutations: {
        // 设置登录状态
        SET_LOGIN_STATUS(state, status) {
            state.isLoggedIn = status
        },

        // 设置用户信息
        SET_USER_INFO(state, userInfo) {
            state.userInfo = userInfo
            state.isLoggedIn = !!userInfo.token
        },

        // 更新会员信息
        UPDATE_MEMBER_INFO(state, memberInfo) {
            state.userInfo.member_info = { ...state.userInfo.member_info, ...memberInfo }
        },

        // 清除用户信息（退出登录）
        CLEAR_USER_INFO(state) {
            state.isLoggedIn = false
            state.userInfo = {
                token: '',
                member_info: {}
            }
        }
    },

    actions: {
        // 登录操作
        async login({ commit }, { token, member_info }) {
            try {
                // 保存到本地存储
                uni.setStorageSync('token', token)
                uni.setStorageSync('member_info', member_info)

                // 更新状态
                commit('SET_USER_INFO', { token, member_info })

                return Promise.resolve()
            } catch (error) {
                console.error('登录状态保存失败:', error)
                return Promise.reject(error)
            }
        },

        // 退出登录
        async logout({ commit }) {
            try {
                // 清除本地存储
                uni.removeStorageSync('token')
                uni.removeStorageSync('member_info')

                // 清除状态
                commit('CLEAR_USER_INFO')

                return Promise.resolve()
            } catch (error) {
                console.error('退出登录失败:', error)
                return Promise.reject(error)
            }
        },

        // 从本地存储恢复登录状态
        async restoreLoginStatus({ commit }) {
            try {
                const token = uni.getStorageSync('token')
                const member_info = uni.getStorageSync('member_info')

                if (token && member_info) {
                    commit('SET_USER_INFO', { token, member_info })
                    console.log('登录状态已恢复')
                } else {
                    commit('CLEAR_USER_INFO')
                    console.log('未发现登录信息')
                }
            } catch (error) {
                console.error('恢复登录状态失败:', error)
                commit('CLEAR_USER_INFO')
            }
        },

        // 更新用户信息
        async updateUserInfo({ commit }, memberInfo) {
            try {
                // 更新本地存储
                const currentMemberInfo = uni.getStorageSync('member_info') || {}
                const updatedMemberInfo = { ...currentMemberInfo, ...memberInfo }
                uni.setStorageSync('member_info', updatedMemberInfo)

                // 更新状态
                commit('UPDATE_MEMBER_INFO', memberInfo)

                return Promise.resolve()
            } catch (error) {
                console.error('更新用户信息失败:', error)
                return Promise.reject(error)
            }
        }
    },

    getters: {
        // 获取登录状态
        isLoggedIn: state => state.isLoggedIn,

        // 获取用户token
        token: state => state.userInfo.token,

        // 获取会员信息
        memberInfo: state => state.userInfo.member_info,

        // 获取显示名称
        displayName: state => {
            const memberInfo = state.userInfo.member_info
            if (memberInfo.MemberName) {
                return memberInfo.MemberName
            }
            if (memberInfo.MemberNickName && memberInfo.MemberNickName !== '微信用户') {
                return memberInfo.MemberNickName
            }
            return '用户'
        },

        // 获取头像
        avatar: state => {
            return state.userInfo.member_info.MemberAvatar || ''
        },

        // 获取会员卡号
        memberCard: state => {
            return state.userInfo.member_info.MemberCardNom || '暂无会员卡'
        },

        // 获取手机号
        memberPhone: state => {
            return state.userInfo.member_info.MemberPhone || ''
        }
    }
})
// #endif

// #ifdef VUE3
import { createStore } from 'vuex'

store = createStore({
    state: {
        // 用户登录状态
        isLoggedIn: false,
        // 用户信息
        userInfo: {
            token: '',
            member_info: {}
        }
    },

    mutations: {
        // 设置登录状态
        SET_LOGIN_STATUS(state, status) {
            state.isLoggedIn = status
        },

        // 设置用户信息
        SET_USER_INFO(state, userInfo) {
            state.userInfo = userInfo
            state.isLoggedIn = !!userInfo.token
        },

        // 更新会员信息
        UPDATE_MEMBER_INFO(state, memberInfo) {
            state.userInfo.member_info = { ...state.userInfo.member_info, ...memberInfo }
        },

        // 清除用户信息（退出登录）
        CLEAR_USER_INFO(state) {
            state.isLoggedIn = false
            state.userInfo = {
                token: '',
                member_info: {}
            }
        }
    },

    actions: {
        // 登录操作
        async login({ commit }, { token, member_info }) {
            try {
                // 保存到本地存储
                uni.setStorageSync('token', token)
                uni.setStorageSync('member_info', member_info)

                // 更新状态
                commit('SET_USER_INFO', { token, member_info })

                return Promise.resolve()
            } catch (error) {
                console.error('登录状态保存失败:', error)
                return Promise.reject(error)
            }
        },

        // 退出登录
        async logout({ commit }) {
            try {
                // 清除本地存储
                uni.removeStorageSync('token')
                uni.removeStorageSync('member_info')

                // 清除状态
                commit('CLEAR_USER_INFO')

                return Promise.resolve()
            } catch (error) {
                console.error('退出登录失败:', error)
                return Promise.reject(error)
            }
        },

        // 从本地存储恢复登录状态
        async restoreLoginStatus({ commit }) {
            try {
                const token = uni.getStorageSync('token')
                const member_info = uni.getStorageSync('member_info')

                if (token && member_info) {
                    commit('SET_USER_INFO', { token, member_info })
                    console.log('登录状态已恢复')
                } else {
                    commit('CLEAR_USER_INFO')
                    console.log('未发现登录信息')
                }
            } catch (error) {
                console.error('恢复登录状态失败:', error)
                commit('CLEAR_USER_INFO')
            }
        },

        // 更新用户信息
        async updateUserInfo({ commit }, memberInfo) {
            try {
                // 更新本地存储
                const currentMemberInfo = uni.getStorageSync('member_info') || {}
                const updatedMemberInfo = { ...currentMemberInfo, ...memberInfo }
                uni.setStorageSync('member_info', updatedMemberInfo)

                // 更新状态
                commit('UPDATE_MEMBER_INFO', memberInfo)

                return Promise.resolve()
            } catch (error) {
                console.error('更新用户信息失败:', error)
                return Promise.reject(error)
            }
        }
    },

    getters: {
        // 获取登录状态
        isLoggedIn: state => state.isLoggedIn,

        // 获取用户token
        token: state => state.userInfo.token,

        // 获取会员信息
        memberInfo: state => state.userInfo.member_info,

        // 获取显示名称
        displayName: state => {
            const memberInfo = state.userInfo.member_info
            if (memberInfo.MemberName) {
                return memberInfo.MemberName
            }
            if (memberInfo.MemberNickName && memberInfo.MemberNickName !== '微信用户') {
                return memberInfo.MemberNickName
            }
            return '用户'
        },

        // 获取头像
        avatar: state => {
            return state.userInfo.member_info.MemberAvatar || ''
        },

        // 获取会员卡号
        memberCard: state => {
            return state.userInfo.member_info.MemberCardNom || '暂无会员卡'
        },

        // 获取手机号
        memberPhone: state => {
            return state.userInfo.member_info.MemberPhone || ''
        }
    }
})
// #endif

export default store